// src/sitemap.service.ts
import { Injectable } from '@nestjs/common';
import { SitemapStream, streamToPromise } from 'sitemap';
import { createWriteStream } from 'fs';
import { join } from 'path';
import { Article } from 'src/entity/article.entity';

@Injectable()
export class SitemapService {
  async generateSitemap() {
    let articleList = await Article.find();

    const smStream = new SitemapStream({
      hostname: 'https://es.callesetas.com',
    });

    const writeStream = createWriteStream(
      join(__dirname, '../../public/sitemap.xml'),
    );

    smStream.pipe(writeStream);

    // 添加网站的 URL
    smStream.write({ url: '/', changefreq: 'daily', priority: 1.0 });
    smStream.write({ url: '/about-us', changefreq: 'monthly', priority: 0.8 });

    // 添加文章的 URL
    articleList.forEach((article) => {
      smStream.write({
        url: `/${article.seoKeywords}`,
        changefreq: 'weekly',
        priority: 0.8,
      });
    });

    smStream.write({
      url: '/1688-purchasing-agent',
      changefreq: 'monthly',
      priority: 0.8,
    });

    smStream.write({
      url: '/china-wholesale-sunglasses-complete-guide',
      changefreq: 'monthly',
      priority: 0.8,
    });

    smStream.write({
      url: '/contact-us',
      changefreq: 'monthly',
      priority: 0.8,
    });

    smStream.write({
      url: '/how-to-buy-wholesale-in-china',
      changefreq: 'monthly',
      priority: 0.8,
    });
    smStream.write({
      url: '/import-top-25-cheap-products-from-china-to-help-you-make-big-money',
      changefreq: 'monthly',
      priority: 0.8,
    });
    smStream.write({
      url: '/yiwu-market-agent',
      changefreq: 'monthly',
      priority: 0.8,
    });

    smStream.end();

    await new Promise((resolve, reject) => {
      writeStream.on('finish', resolve);
      writeStream.on('error', reject);
    });


    const sitemap = await streamToPromise(smStream).then((data) =>
      data.toString(),
    );

    console.log('sitemap', sitemap);

    return sitemap;
  }
}
